<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     block.menu.php
 * Type:     block
 * Name:     menu
 * Purpose:  renders a tree menu
 * -------------------------------------------------------------
 *
 * Expected usage (example):
 * <ul id="menu">
 *     {menu items=$menuItems}
 *     <li>
 *         <a href="#href#" class="number-#index#" title="#title#">#label#</a>
 *         #subblock#
 *         <ul class="submenu-level#level#">
 *             #submenu#
 *         </ul>
 *         #subblock#
 *     </li>
 *     {/menu}
 * </ul>
 *
 * The $menuItems is expected in form:
 * array(
 *     [0] => array(
 *         [href] => link of menu item
 *         [title] => tooltip title of menu item
 *         [label] => label of menu item
 *         [sub] => array( //optional
 *             [0] => array( ... )
 *             [1] => array( ... )
 *             ...
 *         )
 *     )
 *     [1] => array(
 *         ...
 *     )
 *     ...
 * )
 */
function smarty_block_menu($params, $content, &$smarty, &$repeat, $level = 0) {
    if (!isset($params['items']) || !is_array($params['items'])) {
        return '';
    }
    if ($content === null) {
        return '';
    }
    $blocks = explode('#subblock#', $content);
    $result = '';
    foreach ($params['items'] as $index => $item) {
        if (isset($item['sub']) && (count($item['sub']) > 0)) {
            $item['items'] = &$item['sub'];
        }
        $sub = isset($item['items']) ? smarty_block_menu($item, $content,
                $smarty, $repeat, $level + 1) : '';
        $sub = $sub == '' ? '' : preg_replace('/#submenu#/', $sub, $blocks[1]);
        $code = $blocks[0] . $sub . $blocks[2];
        $code = preg_replace('/#href#/', $item['href'], $code);
        $code = preg_replace('/#title#/', $item['title'], $code);
        $code = preg_replace('/#label#/', $item['label'], $code);
        $code = preg_replace('/#index#/', $index, $code);
        $result .= preg_replace('/#level#/', $level, $code);
    }
    return $result;
}
?>
